import { useEffect } from 'react'
import classnames from 'classnames'
import { useDrag } from 'react-dnd'
import { Form } from 'antd'
import { CloseOutlined, CopyOutlined } from '@ant-design/icons'
import inputs from '../../inputs'

// 获取单个表单验证规则
const getFormItemRules = (el) => {
  let result = el.rules || []
  if (el.required) {
    result = [{ required: true, message: `${el.label}不能为空` }].concat(result)
  }
  return result
}

// 表单渲染
const renderInput = (formItem) => {
  // 过滤掉不放在设计中的表单
  const inputTypes = Object.keys(inputs).filter(el => !inputs[el].notInDesign)

  let type = 'text'
  if (formItem.type && inputTypes.includes(formItem.type)) {
    type = formItem.type
  }
  const FormInputName = inputs[type].component
  const inputProps = formItem.inputProps || {}

  return <FormInputName
    {...inputProps}
  ></FormInputName>
}

const DesignFormItem = ({
  item,
  index,
  isFocus,
  onAction,
  onChangeDefaultValue
}) => {

  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'FORM_DESIGNER',
    item: {
      dragType: 'design',
      index: index,
      designItem: item
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    })
  }))

  useEffect(() => {
    if (item.defaultValue !== undefined) {
      onChangeDefaultValue({
        [item.name]: item.defaultValue
      })
    }
  }, [item])

  const handleFocus = () => {
    onAction({
      type: 'focus',
      item: item
    })
  }

  const handleDelete = () => {
    onAction({
      type: 'delete',
      item: item
    })
  }

  const handleCopy = () => {
    onAction({
      type: 'copy',
      index: index
    })
  }

  return <div
    className={classnames(
      'form-design-item',
      { active: isFocus },
      { dragging: isDragging }
    )}
    onClick={e => { e.stopPropagation() }}
  >
    <div
      ref={drag}
      className="form-design-item-mask"
      onClick={handleFocus}
    ></div>
    <div
      className="form-design-item-btns"
      onClick={(e) => { e.stopPropagation() }}
    >
      <span className="btn" onClick={handleCopy}><CopyOutlined /></span>
      <span className="btn" onClick={handleDelete}><CloseOutlined /></span>
    </div>
    <Form.Item
      name={item.name}
      label={item.label}
      rules={getFormItemRules(item)}
      {...item.props}
    >
      {renderInput(item)}
    </Form.Item>
  </div>
}

export default DesignFormItem